import hashlib
from django.http import JsonResponse
from django.shortcuts import render, HttpResponseRedirect, HttpResponse
from shop.models import *
from store.models import GoodsType, Goods
from alipay import AliPay
from redis import *
from Celeryroom.task import send_message
import random


# 用户密码加密
def set_password(pa):
    """
    对用户密码进行加密
    """
    md5 = hashlib.md5()  # import hashlib -- from system_manage.models import *
    md5.update(pa.encode())
    return md5.hexdigest()


# 用户注册
def register(request):
    if request.method == 'POST':
        user_name = request.POST.get('user_name')
        password = request.POST.get('user_cpwd')
        email = request.POST.get('user_email')
        if user_name and password and email:
            user = QUser()
            user.username = user_name
            user.password = set_password(password)
            user.email = email
            user.save()
            return HttpResponseRedirect('/shop/login/')

    return render(request, 'shop/bootstrap_register.html', locals())


# 用户登录
def login(request):
    if request.method == 'POST':
        username = request.POST.get('user_name')
        password = request.POST.get('user_pwd')
        user = QUser.objects.filter(username=username, password=set_password(password)).first()
        if user:
            response = HttpResponseRedirect('/shop/')
            response.set_cookie('user_id', user.id)
            request.session['name'] = user.username
            return response
    return render(request, 'shop/bootstrap_login.html', locals())


# 确认用户登录
def is_login(func):
    def inner(request, *args, **kwargs):
        user_id = request.COOKIES.get('user_id')
        name = request.session.get('name')
        if user_id:
            user = QUser.objects.filter(id=int(user_id)).first()
            if user and user.username == name:
                return func(request, *args, **kwargs)
            else:
                return HttpResponse('非法闯入!')
        else:
            return HttpResponseRedirect('/shop/login/')

    return inner


# 商城首页

def index(request):
    type_list = GoodsType.objects.filter()
    if request.COOKIES.get('user_id'):
        c_user = QUser.objects.filter(id=int(request.COOKIES.get('user_id'))).first()
        number = len(c_user.cart_set.all())
    else:
        number = 0
    return render(request, 'shop/index.html', locals())


# 全部商品页

def goods_list(request, t):
    Type = GoodsType.objects.filter(id=int(t)).first()
    Goods_list = Type.goods_set.all()
    last = Type.goods_set.last().id
    provide_goods = Goods.objects.filter(id__lte=last, g_type=Type.id)[0:2]
    return render(request, 'shop/list.html', locals())


# 商品详情页
def detail(request, t):
    goods = Goods.objects.filter(id=int(t)).first()
    last = goods.g_type.goods_set.last().id
    provide_goods = Goods.objects.filter(id__lte=last, g_type=goods.g_type.id)[0:2]
    glance = Glance()
    if len(Glance.objects.all()) <= 100:
        glance.glance_number = goods.id
        glance.save()
    else:
        for i in Glance.objects.filter(id__gte=Glance.objects.first(), id__lte=Glance.objects.first() + 9).all():
            i.delete()
    return render(request, 'shop/detail.html', locals())


# 添加购物车页
@is_login
def add_cart(request):
    result = {'code': 200, 'message': '加入购物车成功!'}
    if request.method == 'POST':
        UID = int(request.COOKIES.get('user_id'))
        GID = request.POST.get('goods_id')
        number = int(request.POST.get('goods_number'))

        if GID and number:
            c_user = QUser.objects.filter(id=UID).first()
            c_goods = Goods.objects.filter(id=GID).first()
            cart = Cart.objects.filter(c_user=c_user, c_goods=c_goods).first()
            if not cart:
                cart = Cart()
            cart.c_user = c_user
            cart.c_goods = c_goods
            if cart.c_count:
                cart.c_count += number
            else:
                cart.c_count = number
            if cart.c_count <= c_goods.g_number:
                cart.save()
            else:
                result = {'code': 400, 'message': '超出库存警告!'}
        else:
            result = {'code': 400, 'message': '你咋进来的?'}
    return JsonResponse(result)


# 购物车页面
@is_login
def cart(request):
    ID = int(request.COOKIES.get('user_id'))
    c_user = QUser.objects.filter(id=ID).first()
    cart_list = c_user.cart_set.all()
    return render(request, 'shop/bootstrap_cart.html', locals())


# 从购物车中删除商品
@is_login
def cart_del(request):
    t = request.GET.get('t')
    c = Cart.objects.filter(id=int(t)).first()
    if t and c:
        c.delete()
        result = {'code': 200,
                  'message': '删除成功'}
    else:
        result = {'code': 400,
                  'message': '请求的数据不存在'}
    return JsonResponse(result)


# 直接购买确认订单页
@is_login
def place_order(request):
    address = Address.objects.filter(is_default=1).first()
    if request.method == 'POST':
        goods_id = request.POST.get('goods_id')
        goods = Goods.objects.filter(id=int(goods_id)).first()
        goods_number = request.POST.get('goods_number')
        goods_array = [(goods, int(goods_number))]
        count = goods_number
        all_money = int(goods_number) * goods.g_price
    return render(request, 'shop/place_order.html', locals())


# 购物车确定订单页
@is_login
def car_order(request):
    address = Address.objects.filter(is_default=1).first()
    if request.method == 'POST':
        result = request.POST.getlist('result')
        all_goods_id = []
        all_count = []
        if result:
            for i in result:
                result = i.split('+')
                all_goods_id.append(int(result[0]))
                all_count.append(int(result[-1]))
                all_goods = [Goods.objects.filter(id=i).first() for i in all_goods_id]
                goods_array = list(zip(all_goods, all_count))
                count = sum(all_count)
                all_money = sum([i.g_price * j for (i, j) in goods_array])
            return render(request, 'shop/place_order.html', locals())
    return HttpResponseRedirect('/shop/cart/')


# 支付流程
def my_pay(order_number, all_money, case):
    alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
        MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApgThw+/7itSv6AFTXBW6LMxud3ZGYLq2xQMX+S7TaOGKp91fxibu3BHKzEc3GTd0UOjHZDJ72dh0y6Es5z32WAoMPiEBVHnYUgPLoOn1g7PupX13MocjqrV8uS/Sci8jQxs8+sUbym6WWIvmxRcCX/GF0EdF7rETWlMzu9dOAnQPAo+OCZ4ogV20fuXe4GgVBCLTesNUI15USHt7nY1BF1MCBI0QQxM/zWaMlOMpfJjZ2KzJ/qxbhV1TlmAI5solCvDqy0mkSa//bFpkGZyXPJVBWMVxL6QkhjZgSp8gKkb3eKSYCMsweImmlQrKZgaoiZH0fQtadQXN4uL4ySof0wIDAQAB
            -----END PUBLIC KEY-----"""

    app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
        MIIEogIBAAKCAQEAtn3GvuKktc+trQFAhqslmBjq6kVwuVxt/NMRi5aSp7707zilgAR7U3jTu8VNck0CrMQgq8fuWSLI9DgN2yy5s68Xa1jyqRw9flGr/YBemzJ9WXpR17sRwmB2FvxiJkgVKyA9kLpHUIzSErpT85z0Zh7bGyxzfSLEvTGSCcKaxFLTJ1lmHxK1vhTh+GZNMzgZ+d32Kb4kEO7Dzdwkc7cnaZsH8KRsl72IrMQeU/B6UyNyDLzYVd4IgTzfcUsIiAqQ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yC+eBQktclAOP3eGds1wx3u02j+yS+3eB8kEXYSdgLIhd5qBB4d2XAoGANIiQiyzdf93PO93HoYe20yBs1mDk15sucIMzKB+ldOGPNEEvUmr5pLL5S7vrQw176ufHhvZofO33IPiolPiZ6OmCaB29bD8RyR1BTT2nrzAkQ9tDbO7aPJtSbVK8PYPOsYgNgpUJ3ifQJ1iSXltD7Gdt2qL1UySMNz67DdEqrhU=
            -----END RSA PRIVATE KEY-----"""
    alipay = AliPay(
        appid="2016103100781882",
        app_notify_url=None,
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2"
    )
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no=order_number,  # 订单号，自定义，但是不可以重复
        total_amount=str(all_money),  # 支付的金额，必须是字符串
        subject=case,
        return_url="http://127.0.0.1:8000/shop/check_order/",  # 返回结果地址
        notify_url="http://127.0.0.1:8000/shop/check_order/"  # 支付通知的地址
    )
    result = "https://openapi.alipaydev.com/gateway.do?" + order_string
    return result


# 支付页
@is_login
def pay(request):
    result = {'url': '/'}
    if request.method == 'POST':
        pay_method = request.POST.get('pay_method')
        address = request.POST.get('address')
        all_money = request.POST.get('all_money')
        all_goods_id = request.POST.get('all_goods_id')
        if pay_method and address and all_goods_id:
            # check_word = random.randint(10000, 99999)
            # send_message.delay('19817562596', (str(check_word), '5'))
            all_goods_id = all_goods_id.strip(',').split(',')
            all_goods = [Goods.objects.filter(id=int(i)).first() for i in all_goods_id]
            order = Order()
            user = QUser.objects.filter(id=int(request.COOKIES.get('user_id'))).first()
            order.o_user = user
            order.address = address
            order.pay_method = pay_method
            order.all_money = all_money
            order.save()
            order.order_number = str(order.id).zfill(5)
            order.save()
            for i in all_goods:
                order.o_goods.add(i)
            result['url'] = my_pay(order.order_number, all_money, '买生鲜')
            for i in all_goods_id:
                cart = Cart.objects.filter(c_user=user.id, c_goods=int(i))
                cart.delete()
        else:
            result['url'] = '/shop/cart/'
    return JsonResponse(result)


# 确定支付结果
def check_order(request):
    order_number = request.GET.get('out_trade_no')
    order = Order.objects.filter(order_number=order_number).first()
    order.is_trade = 1
    order.save()
    return render(request, 'shop/check_order.html', locals())


# 地址管理
@is_login
def addr_manage(request, t):
    address = Address.objects.filter(id=int(t)).first()
    return render(request, 'shop/edit-address.html', locals())


# 地址编辑
@is_login
def addr_edit(request, t=0):
    if request.method == 'POST':
        acc_name = request.POST.get('acc_name')
        acc_addr = request.POST.get('acc_addr')
        acc_post = request.POST.get('acc_post')
        acc_phone = request.POST.get('acc_phone')
        is_default = request.POST.get('is_default')
        if acc_name and acc_addr and acc_phone and acc_post:
            if t:
                address = Address.objects.filter(id=int(t)).first()
            else:
                address = Address()
            if is_default:
                addre = Address.objects.filter(is_default=1).first()
                if addre:
                    addre.is_default = 0
                    addre.save()
                address.is_default = 1
            else:
                address.is_default = 0
            address.acc_name = acc_name
            address.acc_addr = acc_addr
            address.acc_post = acc_post
            address.acc_phone = acc_phone
            address.add_QuUer = QUser.objects.filter(id=int(request.COOKIES.get('user_id'))).first()
            address.save()
    return HttpResponseRedirect('/shop/usercenter')


# 我的订单页
@is_login
def my_orders(request):
    user = QUser.objects.filter(id=int(request.COOKIES.get('user_id'))).first()
    yet_order_list = user.order_set.filter(is_trade=0).all()
    done_order_list = user.order_set.filter(is_trade=1).all()
    return render(request, 'shop/myorders.html', locals())


# 删除订单
@is_login
def delete_order(request, t):
    order = Order.objects.filter(id=int(t))
    order.delete()
    return HttpResponseRedirect('/shop/myorders/')


# 订单页去付款
def re_pay(request, t):
    order = Order.objects.filter(id=int(t)).first()
    url = my_pay(order.order_number, order.all_money, '买生鲜')
    return HttpResponseRedirect(url)


# 用户中心页
@is_login
def user_center(request):
    ID = request.COOKIES.get('user_id')
    user = QUser.objects.filter(id=ID).first()
    address_list = user.address_set.all()
    user = QUser.objects.filter(id=int(request.COOKIES.get('user_id'))).first()
    yet_order_list = user.order_set.filter(is_trade=0).all()
    done_order_list = user.order_set.filter(is_trade=1).all()
    recent_glance_list = []
    glance_list = [Goods.objects.filter(id=i.glance_number).first() for i in Glance.objects.all()]
    for i in glance_list:
        if i not in recent_glance_list:
            recent_glance_list.append(i)
        else:
            recent_glance_list.remove(i)
            recent_glance_list.append(i)
    recent_glance_list = recent_glance_list[::-1]
    if len(recent_glance_list) > 4:
        recent_glance_list = recent_glance_list[0:4]
    return render(request, 'shop/user-center-info.html', locals())


# 用户编辑
@is_login
def edit_user(request):
    user_id = int(request.COOKIES.get('user_id'))
    user = QUser.objects.filter(id=user_id).first()
    if request.method == 'POST':
        name = request.POST.get('name')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        if name and phone and address:
            user.username = name
            user.quserinfo.phone = phone
            user.quserinfo.address = address
            user.save()
            user.quserinfo.save()
            return HttpResponseRedirect('/shop/usercenter/')
    return render(request, 'shop/edit-user.html', locals())


# 搜索商品
def seek(request):
    if request.method == 'POST':
        g = request.POST.get('goods')
        goods = Goods.objects.filter(g_name__contains=g).first()
        if goods:
            return render(request, 'shop/detail.html', locals())
        else:
            return render(request,'shop/none.html')



# {% extends 'shop/base.html' %}
# {% block title %}
#
# {% endblock %}
# {% block style%}
#
# {% endblock %}
# {% block lable %}
#
# {% endblock %}
# {% block contenter %}
#
# {% endblock %}
# {% block script %}
#
# {% endblock %}
